package com.jack.helloworld.liveWallpaper;

import android.media.MediaPlayer;
import android.view.Surface;

/**
 * Created by xiaofeng on 2017/4/26.
 */

public class VideoLiveWallpaperMediaManager {

    private static MediaPlayer sMediaPlayer;
    private static int sPosition = 0;

    public static void play(String path, boolean isLoop, int position, boolean hasVoice, Surface surface, MediaPlayer.OnCompletionListener listener) {

        if (sMediaPlayer == null) {
            sMediaPlayer = new MediaPlayer();
        } else {
            sMediaPlayer.reset();
        }

        if (listener != null) {
            sMediaPlayer.setOnCompletionListener(listener);
        }
        sMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                sMediaPlayer.reset();
                return false;
            }
        });
        try {
            sMediaPlayer.setDataSource(path);
            sMediaPlayer.setLooping(isLoop);
            if (hasVoice) {
                sMediaPlayer.setVolume(1.0f, 1.0f);
            } else {
                sMediaPlayer.setVolume(0, 0);
            }
            sMediaPlayer.setSurface(surface);
            sMediaPlayer.prepare();
            sMediaPlayer.seekTo(position);
            sMediaPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void pause() {
        if (sMediaPlayer != null && sMediaPlayer.isPlaying()) {
            sPosition = sMediaPlayer.getCurrentPosition();
            sMediaPlayer.pause();
        }
    }

    public static void resume() {
        if (sMediaPlayer != null) {
            sMediaPlayer.start();
        }
    }

    public static void release() {
        if (sMediaPlayer != null) {
            if (sMediaPlayer.isPlaying()) {
                sMediaPlayer.stop();
            }
            sMediaPlayer.release();
            sMediaPlayer = null;
        }
    }

    public static void voiceNormal() {
        if (sMediaPlayer != null) {
            sMediaPlayer.setVolume(1.0f, 1.0f);
        }
    }

    public static void voiceSilence() {
        if (sMediaPlayer != null) {
            sMediaPlayer.setVolume(0, 0);
        }
    }
}
